package com.zxzw.scanningin.http

import android.util.Log
import com.zxzw.scanningin.http.service.ApiService
import com.zxzw.scanningin.http.service.DownloadService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * 发起http请求方式一
 * @param description 说明描述
 * @param request 请求的挂起函数
 */
suspend fun <T> request(
    description: String = "",
    request: suspend ApiService.() -> T?
): Flow<ApiResponse<T>> {
    return flow {
        val response = request(getRetrofit(AppConfig.baseUrl).create(ApiService::class.java))
            ?: throw IllegalArgumentException("数据非法，获取响应数据为空")
        emit(response)
    }.onStart {
        description.takeIf { it != "" }?.apply {
            Log.e("<<<<","请求描述：$description")
        }
    }.map {
        val result: T = it
        ApiResponse(result, null)
    }.flowOn(Dispatchers.IO).catch { e ->
        Log.e("<<<<","")
        emit(ApiResponse(null, e))
    }
}

/**
 * 发起http请求方式二
 * @param scope 协程作用域
 * @param request 请求的挂起lambda函数
 * @param response 请求结果lambda函数
 * @param description 说明描述
 */
fun <T> request2(
    scope: CoroutineScope,
    request: suspend ApiService.() -> T?,
    response: (ApiResponse<T>) -> Unit,
    description: String = ""
) {
    scope.launch {
        flow<ApiResponse<T>> {
            request.invoke(getRetrofit(AppConfig.baseUrl).create(ApiService::class.java))?.also {
                emit(ApiResponse(it, null))
            }
        }.onStart {
            description.takeIf { it != "" }?.apply {
                Log.e("<<<<","请求描述：$description")
            }
        }.catch {
            emit(ApiResponse(null, it))
        }.collect {
            response(it)
        }
    }
}

/**
 * 下载文件
 * @param description 说明描述
 * @param request 请求的挂起函数
 */
suspend fun <T> download(
    description: String = "",
    request: suspend DownloadService.() -> T?
): Flow<ApiResponse<T>> {
    return flow {
        val response =
            request(getDownloadRetrofit(AppConfig.baseUrl).create(DownloadService::class.java))
                ?: throw IllegalArgumentException("数据非法，获取响应数据为空")
        emit(response)
    }.onStart {
        description.takeIf { it != "" }?.apply {
            Log.e("<<<<","请求描述：$description")
        }
    }.map {
        val result: T = it
        ApiResponse(result, null)
    }.flowOn(Dispatchers.IO).catch { e ->
        emit(ApiResponse(null, e))
    }
}